package com.example.search.service.impl;

import com.example.search.pojo.UserSearch;
import com.example.search.service.UserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserSearchServiceImpl implements UserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        // 1、查询当前用户的搜索关键词
        if (userId == null) {
            log.info("用户未登录，无法记录搜索历史");
            return;
        }
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        UserSearch userSearch = mongoTemplate.findOne(query, UserSearch.class);

        //2、存在，更新创建时间
        if (userSearch != null) {
            log.info("该搜索词已存在：{}", keyword);
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        // 3、不存在，判断当前历史记录总数量是否超过10
        userSearch = new UserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        // 4、获取当前用户记录条数
        query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime"));;
        List<UserSearch> userSearchList = mongoTemplate.find(query, UserSearch.class);
        if (userSearchList == null || userSearchList.size() < 10) {
            mongoTemplate.save(userSearch);
        } else {
            // 获取时间最小的一条
            UserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), userSearch);
        }
    }
}
